package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpSession session;

    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //接受请求参数
        String username = map.get("username");
        String password = map.get("password");
        //2.调用service登录操作
        ResultInfo resultInfo = employeeService.login(username, password);
        //3.如果登陆成功向session中保存一个标识
        if (resultInfo.getCode() == 1) {
            Employee employee = (Employee) resultInfo.getData();
            session.setAttribute(Constant.SESSION_EMPLOYEE, employee);
        }
        return resultInfo;
    }

    @PostMapping("/employee/logout")
    public ResultInfo logout() {
        //1销毁session
        session.invalidate();
        return ResultInfo.success(null);
    }

    @GetMapping("/employee/find")
    public ResultInfo find(String name) {
        //调用service查询
        List<Employee> employeeList = employeeService.findByName(name);
        //封装返回结果
        return ResultInfo.success(employeeList);
    }

    @PostMapping("/employee")
    public ResultInfo add(@RequestBody Employee employee) {
        employeeService.save(employee);
        return ResultInfo.success(null);
    }

    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee) {
        employeeService.update(employee);
        return ResultInfo.success(null);
    }

}
